package com.nirvana.admin.service.impl;

import cn.hutool.core.util.IdUtil;
import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.nirvana.admin.constant.RedisConstants;
import com.nirvana.admin.constant.SecurityConstants;
import com.nirvana.admin.entity.SysMenu;
import com.nirvana.admin.entity.SysRole;
import com.nirvana.admin.entity.SysUser;
import com.nirvana.admin.entity.SysUserRole;
import com.nirvana.admin.entity.vo.AuthInfoResponseVO;
import com.nirvana.admin.entity.vo.AuthMenuResponseVO;
import com.nirvana.admin.entity.vo.AuthRequestVO;
import com.nirvana.admin.entity.vo.LoginUser;
import com.nirvana.admin.mapper.SysUserRoleMapper;
import com.nirvana.admin.service.AuthService;
import com.nirvana.admin.service.CaptchaService;
import com.nirvana.admin.service.SysMenuService;
import com.nirvana.admin.service.SysRoleService;
import com.nirvana.admin.service.SysUserService;
import com.nirvana.admin.util.SecurityUtils;
import com.nirvana.common.constant.BaseMessage;
import com.nirvana.common.util.RedisUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.context.annotation.Lazy;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.authentication.BadCredentialsException;
import org.springframework.security.authentication.DisabledException;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;
import org.springframework.util.Assert;

import javax.annotation.Resource;
import java.util.Comparator;
import java.util.Date;
import java.util.List;
import java.util.Set;
import java.util.stream.Collectors;

/**
 * 认证服务实现类
 *
 * @author zhangshuaiyin
 * @date 2021-09-29 14:38
 */
@Slf4j
@Service
public class AuthServiceImpl implements AuthService {

    // 延迟加载，因为存在相互依赖的问题
    @Resource
    @Lazy
    private AuthenticationManager authenticationManager;
    @Resource
    private CaptchaService captchaService;
    @Resource
    private RedisUtils redisUtils;

    @Resource
    private SysUserRoleMapper userRoleMapper;
    @Resource
    private SysMenuService menuService;
    @Resource
    private SysRoleService roleService;
    @Resource
    private SysUserService userService;

    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        // 获取 username 对应的 SysUser
        SysUser user = userService.getUserByUsername(username);
        if (user == null) {
            throw new UsernameNotFoundException(username);
        }
        // 创建 LoginUser 对象
        return user.convertLoginUser();
    }

    @Override
    public String login(AuthRequestVO requestVO, String userIp, String userAgent) {
        // 判断验证码是否正确
        this.verifyCaptcha(requestVO.getUsername(), requestVO.getUuid(), requestVO.getCode());

        // 使用账号密码，进行登陆。
        // 用户验证
        Authentication authentication;
        try {
            // 调用 Spring Security 的 AuthenticationManager#authenticate(...) 方法，使用账号密码进行认证
            // 在其内部，会调用到 loadUserByUsername 方法，获取 User 信息
            authentication = authenticationManager.authenticate(new UsernamePasswordAuthenticationToken(requestVO.getUsername(), requestVO.getPassword()));
        } catch (BadCredentialsException badCredentialsException) {
            throw BaseMessage.AUTH_LOGIN_BAD_CREDENTIALS.exception();
        } catch (DisabledException disabledException) {
            throw BaseMessage.AUTH_LOGIN_USER_DISABLED.exception();
        } catch (AuthenticationException authenticationException) {
            log.error("[login][username({}) 发生未知异常]", requestVO.getUsername(), authenticationException);
            throw BaseMessage.AUTH_LOGIN_FAIL_DEFAULT.exception();
        }

        // 登陆成功
        Assert.notNull(authentication.getPrincipal(), "Principal 不会为空");
        LoginUser loginUser = (LoginUser) authentication.getPrincipal();

        // 获取用户角色列表
        loginUser.setRoleIds(getUserRoleIds(loginUser));
        loginUser.setUpdateTime(new Date());

        // 生成 token
        String token = IdUtil.fastSimpleUUID();
        // 缓存登陆用户到 Redis 中，返回 sessionId 编号
        redisUtils.set(RedisConstants.LOGIN_USER + token, loginUser, 300000);
        return token;
    }

    @Override
    public AuthInfoResponseVO getPermissionInfo() {
        LoginUser loginUser = SecurityUtils.getLoginUser();
        if (loginUser == null) {
            return null;
        }
        // 1. 获取用户信息
        SysUser user = userService.getById(loginUser.getId());
        // 2. 获取角色信息
        List<SysRole> roleList = roleService.listByIds(getUserRoleIds(loginUser));
        // 3. 获取菜单信息 目录、菜单、按钮
        List<SysMenu> menuList = menuService.getList(roleList);

        return AuthInfoResponseVO
                .builder()
                .user(AuthInfoResponseVO.UserVO.builder().nickname(user.getNickname()).avatar(user.getAvatar()).build())
                .roles(roleList.stream().map(SysRole::getCode).collect(Collectors.toSet()))
                .permissions(menuList.stream().map(SysMenu::getPermission).collect(Collectors.toSet()))
                .build();
    }

    @Override
    public List<AuthMenuResponseVO> getRouters() {
        return menuService.getRouters();
    }

    private Set<Long> getUserRoleIds(LoginUser loginUser) {
        List<SysUserRole> userRoleList = userRoleMapper.selectList(new LambdaQueryWrapper<SysUserRole>().eq(SysUserRole::getUserId, loginUser.getId()));
        return userRoleList.stream().map(SysUserRole::getRoleId).collect(Collectors.toSet());
    }

    @Override
    public LoginUser verifyTokenAndRefresh(String token) {
        LoginUser loginUser = JSON.parseObject(JSON.toJSONString(redisUtils.get(RedisConstants.LOGIN_USER + token)), LoginUser.class);
        if (loginUser == null) {
            return null;
        }
        // 刷新 LoginUser 缓存
        this.refreshLoginUserCache(token, loginUser);
        return loginUser;
    }

    private void refreshLoginUserCache(String token, LoginUser loginUser) {
        // 每 1/3 的 Session 超时时间，刷新 LoginUser 缓存
        if (System.currentTimeMillis() - loginUser.getUpdateTime().getTime() < SecurityConstants.TOKEN_EXPIRE_TIME.toMillis() / 3) {
            return;
        }

        // 重新加载 SysUser 信息
        SysUser user = userService.getById(loginUser.getId());
        if (user == null || Integer.valueOf(1).equals(user.getStatus())) {
            // 校验 token 时，用户被禁用的情况下，也认为 token 过期，方便前端跳转到登陆界面
            throw BaseMessage.AUTH_LOGIN_TOKEN_EXPIRED.exception();
        }

        // 刷新 LoginUser 缓存
        loginUser.setDeptId(user.getDeptId());
        loginUser.setRoleIds(this.getUserRoleIds(loginUser));
        loginUser.setUpdateTime(new Date());
        redisUtils.set(RedisConstants.LOGIN_USER + token, loginUser);
    }

    @Override
    public void logout(String token) {
        // 查询用户信息
        LoginUser loginUser = JSON.parseObject(JSON.toJSONString(redisUtils.get(RedisConstants.LOGIN_USER + token)), LoginUser.class);
        if (loginUser == null) {
            return;
        }
        // 删除 session
        redisUtils.del(RedisConstants.LOGIN_USER + token);
    }

    private void verifyCaptcha(String username, String captchaId, String captchaCode) {
        String code = captchaService.getCaptchaCode(captchaId);
        // 验证码不存在
        if (code == null) {
            // TODO 创建登陆失败日志（验证码不存在）
            // this.createLoginLog(username, SysLoginResultEnum.CAPTCHA_NOT_FOUND);
            throw BaseMessage.AUTH_LOGIN_CAPTCHA_NOT_FOUND.exception();
        }
        // 验证码不正确
        if (!code.equals(captchaCode)) {
            // TODO 创建登陆失败日志（验证码不正确)
            // this.createLoginLog(username, SysLoginResultEnum.CAPTCHA_CODE_ERROR);
            throw BaseMessage.AUTH_LOGIN_CAPTCHA_ERROR.exception();
        }
        // 正确，所以要删除下验证码
        captchaService.deleteCaptchaCode(captchaId);
    }
}
